<?php
	defined("AT_EXE") or die ("CORE VARIABLE IS NOT DEFINED.");
	class GalleryController extends Controller {
		public function __construct(){
			$this->calledClass(get_class($this));
		}
		public function index(){
			Basic::pr( Basic::getFolders("./data/galleries/chamroeun") );
			Basic::pr( Basic::getFiles("./data/galleries/chamroeun") );
		}
		public function delete(){
			$ids = ($ids=$this->get("ids"))!=NULL?is_array($ids)?$ids:explode(",",$ids):array();
			if(!empty($ids)){
				$gallery = $this->loadModel("Gallery");
				$records = $gallery->deletephoto($ids);
				if($records!==false){
					foreach($records as $record)
						Basic::fileExist($record->location)?
							Basic::deleteFile($record->location):
								false;
					echo "Photo(s) is/are delete successfully";
				}else{
					echo "There is no photo to delete";
				}
			}else{
				echo "There is no photo request to delete.";
			}
			$this->refresh(array("com"=>"gallery","action"=>"photo"));
		}
		public function photo(){
			$gallery = $this->loadModel("Gallery");
			$this->set(array("photos"=>$gallery->getList(1,20)));
			$this->render("index");
		}
		public function upload(){
			Import::util("FileUpload");
			$user_id = 2;
			$user = "vitou";
			$folder = "data/galleries/".$user ;
			if(!Basic::fileExist($folder))Basic::createFolder($folder);
			$gallery = $this->loadModel("Gallery");
			$infos=FileUpload::checkFileUpload($folder);
			$helper = true;
			foreach($infos as $info ){
				if($info["error"]["number"]==0){
					if(($record=$gallery->savephoto(array("uid"=>$user_id,"name"=>$info["name"],"location"=>"","type"=>$info["type"],"size"=>$info["size"],"d_w"=>$info["dimension"]["width"],"d_h"=>$info["dimension"]["height"],"created"=>date("Y-m-d H:s:i"),"modified"=>date("Y-m-d H:s:i"))))!==false){
						echo $record->id . "<br/>" ;
						$gallery->update(array("location"=>$folder."/".$record->id.".".$info["ext"]),array("id"=>$record->id));
						FileUpload::uploadFile($info["control"],$record->id.".".$info["ext"],5,$folder);
					}else{
						Basic::eco("<br/>There is an unexpected error occured during upload file.<br/>");
						Basic::pr($info);
						$help=false;
					}
				}
				else{
					// check error 
				}
			}
			if($helper)echo "All file(s) are/is uploaded successfully.";
			$this->refresh(array("com"=>"gallery","action"=>"photo"));
		}
	}